<template>
  <el-dialog center title="新增师傅" :visible.sync="innerVisible" width="1011px">
    <el-form v-loading="dialogLoading" :model="search" :label-position="labelPosition" :rules="rules" ref="ruleForm" label-width="110px">
      <el-row>
        <el-col :span="10" :offset="1">
          <el-form-item  label="输入手机号：" prop="workerPhone">
            <el-input v-model.trim="search.workerPhone"  clearable style="position:relative;" placeholder="请输入要添加的手机号">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col class="text-center" :span="3" :offset="1">
          <el-button type="primary" style="width:100%" @click.prevent="searchFunc(search)">搜索</el-button>
        </el-col>
        <!--错误提示-->
        <el-col :span="24" style="margin-bottom:10px;">
          <div v-if="errorMessage" class="help-block font-red text-center" style="color:red">{{ errorMessage }}</div>
        </el-col>
      </el-row>
      <!--表格-->
      <el-row>
        <el-table
          ref="elTable"
          :data="mergeData"
          border
          :span-method="objectSpanMethod"
        >
          <el-table-column
            align="center"
            prop="index"
            label="#"
            width="60"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="name"
            label="姓名"
            width="85"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="registerPhone"
            width="115"
            label="手机号">
          </el-table-column>
          <el-table-column
            align="center"
            width="170"
            prop="province/city"
            label="服务范围">
            <template slot-scope="scope">{{ scope.row.province }} {{ scope.row.city }}</template>
          </el-table-column>
          <el-table-column
            align="center"
            width="180"
            prop="businessName"
            label="业务类型">
          </el-table-column>
          <el-table-column
            align="center"
            width="350"
            prop="serviceName"
            label="服务类型">
          </el-table-column>
        </el-table>
      </el-row>
      <!--按钮-->
      <el-row style="margin-top: 20px;">
        <el-col class="text-center" :span="5" :offset="6">
          <el-button @click="innerVisible = false" style="width:100%">取消</el-button>
        </el-col>
        <el-col class="text-center" :span="5" :offset="1">
          <el-button type="primary" @click="submit" :disabled="!tableData.length" style="width:100%">绑定</el-button>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<script>
import {dotData, confirm} from '@/utils'
import {isPhone} from '@/utils/validate'
import lodash from 'lodash'
// import L from 'lodash'
export default {
  components: {
  },
  props: {
    // id: {
    //   type: String,
    //   default: ''
    // },
    visible: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    visible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (val) {
        // 重置表单
        this.resetFields()
        this.search.workerPhone = ''
        this.errorMessage = ''
      }
      this.innerVisible = val
    },
    // 如果内部有新值变化，更新外部visible
    innerVisible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      this.$emit('update:visible', val)
    }
  },
  data() {
    return {
      dialogLoading: false,
      innerVisible: this.visible,
      labelPosition: 'left',
      search: {
        workerPhone: ''
      },
      tableData: [{}],
      btnLoading: false,
      errorMessage: '',
      rules: {
        workerPhone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: isPhone, message: '手机格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    mergeData() {
      return lodash.flatten(this.tableData.map((v, i) => {
        if (Array.isArray(v.serviceBusinesses)) {
          return v.serviceBusinesses.map((item, j) => Object.assign({}, item, v, {
            index: i + 1,
            showFlag: j === 0,
            mergeLength: v.serviceBusinesses.length
          }))
        } else {
          return Object.assign({}, v, {
            index: i + 1,
            showFlag: true,
            mergeLength: 1
          })
        }
      }))
    }
  },
  methods: {
    isPhone,
    searchFunc(search) {
      this.$refs.ruleForm.validate().then((result) => {
        if (result) {
          this.httpSuccessGetTest()
        }
      })
    },
    httpSuccessGetTest() {
      this.$ajax.get('/ms-fahuobao-app/workerUser/getWorkerByNameAndPhone', {name: this.search.workerPhone}).then(response => {
        if (response && response.success) {
          if (response.data) {
            if (Array.isArray(response.data) && response.data.length) {
              this.tableData = [response.data[0]]
            } else {
              this.tableData = [response.data]
            }
            this.errorMessage = ''
          } else {
            this.tableData = []
            this.errorMessage = '很抱歉！未能查询到你输入的手机号对应的师傅，请输入正确的手机号。'
          }
        }
      })
    },
    // 修改时，http请求出该id 的详情数据 并回填
    getDetail() {
      this.dialogLoading = true
      this.$ajax.get('/ms-fahuobao-user/defaultPickupInfo/get-pickup-info-by-id', {id: this.id}).then(response => {
        const success = response.success
        if (success) {
          this.callBackData = response.data || {}
          console.log('22222', this.callBackData)
          this.model.deliveryName = dotData(this.callBackData, 'deliveryName')
          this.model.deliveryPhone = this.callBackData.deliveryPhone
          this.model.deliveryAddress = this.callBackData.deliveryAddress
          this.model.isDefault = this.callBackData.isDefault
          if (this.callBackData.deliveryProvinceNo && this.callBackData.deliveryCityNo && this.callBackData.deliveryDistrictNo) {
            this.model.address = [
              this.callBackData.deliveryProvinceNo,
              this.callBackData.deliveryCityNo,
              this.callBackData.deliveryDistrictNo
              // {id: this.callBackData.deliveryProvinceNo, text: this.callBackData.deliveryProvince},
              // {id: this.callBackData.deliveryCityNo, text: this.callBackData.deliveryCity},
              // {id: this.callBackData.deliveryDistrictNo, text: this.callBackData.deliveryDistrict}
            ]
          }
          console.log('this.model.address', this.model.address)
        }
      }).finally(_ => {
        this.dialogLoading = false
      })
    },
    submit() {
      this.innerVisible = false // 隐藏父弹框
      // this.$refs.addModalFrame.show() // 显示子弹框
      this.btnLoading = true
      let url = '/ms-fahuobao-order/FhbMyWorker/binding'
      let postData = {}
      if (this.tableData.length !== 0) {
        postData.workerPhone = this.tableData[0].registerPhone
        confirm('<p>你确定要绑定该条师傅信息？</p>', '温馨提示', {
          type: 'warning',
          center: true,
          dangerouslyUseHTMLString: true,
          confirmButtonLoading: true,
          confirmCallBack: ({confirmButtonLoadingClose, close}) => {
            this.$ajax.post(url, postData).then(response => {
              const success = dotData(response, 'success')
              if (success) {
                this.$emit('refresh', true)
                close().finally(_ => {
                  confirm('绑定成功', undefined, {type: 'success'})
                })
              }
            }).finally(_ => {
              confirmButtonLoadingClose()
            })
          }
        })
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 要合并的列 type:index
      let columnIndependent = ['businessName', 'serviceName']
      if (columnIndependent.indexOf(column.property) < 0) {
        if (row.showFlag) {
          return {
            rowspan: row.mergeLength,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },
    resetFields() {
      if (this.$refs['ruleForm']) {
        this.$refs['ruleForm'].resetFields()
      }
    }
  }
}
</script>
